/**
 * Description: socket 服务端 - 使用read读取信息
 * File: server.c |Time: 2021-04-09 19:26
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>


int main(int argc, char *argv[])
{
    // 使用socket函数申请socket文件描述符
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    // 给socket分配主机名与端口号
    struct sockaddr_in sockaddr, clientaddr;
    struct in_addr server_ip;
    
    int res = inet_aton("192.168.1.145", &server_ip);
    if (res == -1) {
        printf("invalid ip address.\n");
        return -1;
    }


    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(1122);
    sockaddr.sin_addr = server_ip;

    bind(
            sockfd, 
            (struct sockaddr *)&sockaddr, 
            sizeof(struct sockaddr)
    );
   
    // 启动socket监听状态
    if (listen(sockfd, 5) == -1) {
        perror("listen");
        return -1;
    }


    while(1) {

        // 阻塞等待客户端的连接
        socklen_t address_len;
        int recvfd = accept(sockfd, (struct sockaddr*)&clientaddr, &address_len);
        if (-1 == recvfd) {
            perror("accept");
            return -1;
        }

        pid_t pid = fork();

        if (pid > 0) {
            continue;
        }

        printf("[client] ip:%s port:%d\n", 
            inet_ntoa(clientaddr.sin_addr), 
            clientaddr.sin_port
            );

        char buf[100] = {0};
        read(recvfd, buf, 100);

        printf("receive from client: %s\n", buf);
    }

    return 0;
}
